<template>
  <div class="dashboard">
    <el-container class="dashboard-container">
      <el-aside width="280px" style="height: 100%">
        <el-menu
            style="height: 100%"
            :default-active="activeIndex"
        >
          <template v-for="item in items">
            <el-menu-item v-if="item.show === 'admin' ? isAdmin : isUser" :index="item.index" :key="item.index">
              <span slot="title">{{ item.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>

      <el-main v-loading="loading" element-loading-background="#FFFFFF">
        <div class='setting-container'>
          <!-- 用户名及密码 -->
          <div class='setting-box' id='identity' style="padding-bottom: 0">
            <div class='setting-label'>用户名及密码 修改</div>
            <el-form :inline="true" :model="identitySetting.form">
              <el-form-item label="用户名:">
                <el-input v-model="identitySetting.form.username" :disabled="!identitySetting.form.updatingUsername" size="mini"></el-input>
              </el-form-item>
              <span class="icon-container">
                                <!-- 用户名编辑按钮 -->
                                <i class="el-icon-edit"
                                   v-if="!identitySetting.form.updatingUsername"
                                   @click="editUsername"
                                ></i>
                                <el-button type="text" v-else @click="updateUsername">完成</el-button>
                            </span>
              <el-form-item label="密码:">
                <el-input
                    v-model="identitySetting.form.password"
                    :disabled="!identitySetting.form.updatingPassword"
                    size="mini"
                    :type="identitySetting.form.updatingPassword ? 'text' : 'password'"
                ></el-input>
              </el-form-item>
              <span class="icon-container">
                                <!-- 密码编辑按钮 -->
                                <i class="el-icon-edit"
                                   v-if="!identitySetting.form.updatingPassword"
                                   @click="editPassword"
                                ></i>
                                <el-button type="text" v-else @click="updatePassword">完成</el-button>
                            </span>
            </el-form>
          </div>

          <!-- 项目权限管理 -->
          <div class='setting-box' id='permission' v-if="isAdmin">
            <div class='setting-label'>项目权限管理</div>
            <el-form :inline="true">
              <el-form-item label="项目模块:" style="margin-bottom: 0">
                <el-select style="width: 400px" size="mini" v-model="permissionSetting.selectedProject" placeholder="请选择">
                  <el-option v-for="module in modules"
                             :key="'perm-' + module"
                             :label="module"
                             :value="module">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-button size="small" @click="permissionConfigureUser('leader')">配置项目负责人</el-button>
              <el-button size="small" @click="permissionConfigureUser('member')">配置项目组成员</el-button>
            </el-form>
          </div>

          <!-- 用户管理 -->
          <div class='setting-box' id='users' v-if="isAdmin">
            <div class='setting-label'>用户管理</div>
            <el-form :inline="true" @submit.native.prevent>
              <el-form-item label="查找用户:" style="margin-bottom: 0">
                <el-input size="mini" placeholder="输入用户名，按回车确认" suffix-icon="el-icon-search" style="width: 200px"
                          v-model="userSetting.searchForm.value"
                          @keyup.enter.native="searchMember"
                          :disabled="userSetting.loading"
                />
              </el-form-item>
            </el-form>
            <el-table border style="width: 500px; margin: 10px 0" :header-cell-style="{backgroundColor: '#F3F3F3'}"
                      v-loading="userSetting.loading"
                      :data="userSetting.list">
              <el-table-column prop="id" label="编号" width="50"></el-table-column>
              <el-table-column prop="name" label="姓名" width="100"></el-table-column>
              <el-table-column prop="module" label="所属模块"></el-table-column>
            </el-table>
            <el-button icon="el-icon-circle-plus-outline" @click="showAddUser">新增用户</el-button>
          </div>

          <!-- 项目运行日志查看 -->
          <div class='setting-box' id='logs' v-if="isAdmin">
            <div class='setting-label'>项目运行日志查看</div>
            <el-form :inline="true" :disabled="logSetting.loading">
              <el-form-item label="项目模块:" style="margin-bottom: 0">
                <el-select style="width: 400px" size="mini" v-model="logSetting.selectedProject" @change="loadLog" placeholder="请选择">
                  <el-option v-for="module in modules"
                             :key="'log-' + module"
                             :label="module"
                             :value="module">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <el-table border v-loading="logSetting.loading" :data="logSetting.logs" style="width: 700px; margin: 10px 0" :header-cell-style="{backgroundColor: '#F3F3F3'}">
              <el-table-column prop="marker" label="级别" width="100">
                <template slot-scope="scope">
                  <div class="info" v-if="scope.row.marker.toUpperCase().includes('INFO')">{{scope.row.marker.trim()}}</div>
                  <div class="warn" v-else-if="scope.row.marker.toUpperCase().includes('WARN')">{{scope.row.marker.trim()}}</div>
                  <div class="error" v-else-if="scope.row.marker.toUpperCase().includes('ERROR')">{{scope.row.marker.trim()}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="info" label="操作"></el-table-column>
              <el-table-column prop="time" label="日期" width="150"></el-table-column>
            </el-table>
            <!-- 分页按钮 -->
            <el-pagination
                background
                :disabled="logSetting.loading"
                @size-change="changeLogPageSize"
                @current-change="changeLogPage"
                :current-page="logSetting.currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="logSetting.pageSize"
                layout="prev, pager, next, sizes, jumper"
                :page-count="logSetting.pageNum">
            </el-pagination>
          </div>

        </div>

      </el-main>
    </el-container>
    <!--  用户管理模块添加新用户  -->
    <el-dialog title="添加新用户" :visible.sync="userSetting.dialog.visible" width="520px">
      <el-form :model="userSetting.dialog.form" v-loading="userSetting.dialog.loading">
        <el-form-item>
          <el-input v-model="userSetting.dialog.form.username" placeholder="请输入用户名" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="userSetting.dialog.form.password" placeholder="请输入用户密码" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="userSetting.dialog.form.password2" placeholder="请再次输入用户密码" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 0">
          <el-select style="width: 300px" v-model="userSetting.dialog.form.selectedProject" placeholder="请选择">
            <el-option v-for="module in modules"
                       :key="'useradd-' + module"
                       :label="module"
                       :value="module">
            </el-option>
          </el-select>
          <el-radio style="margin-left: 10px" v-model="userSetting.dialog.form.position" label="leader">负责人</el-radio>
          <el-radio v-model="userSetting.dialog.form.position" label="member">成员</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUser" :loading="userSetting.dialog.loading" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!--  权限管理模块配置负责人或者成员  -->
    <el-dialog  width="380px"
        :title="permissionDialogTitle"
        :visible.sync="permissionSetting.configDialog.visible"
        >
      <el-table
          :data="permissionSetting.configDialog.users"
          :header-cell-style="{backgroundColor: '#F3F3F3'}"
          v-loading="permissionSetting.configDialog.loading"
          element-loading-background="#FFFFFF"
      >
        <el-table-column prop="id" label="编号" width="60"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="position" label="权限">
          <span>{{ permissionSelectedRole }}</span>
        </el-table-column>
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <i @click="deletePosition(scope.$index)" class="el-icon-delete icon-button icon-button-danger"></i>
          </template>
        </el-table-column>
      </el-table>
      <div class="custom-button icon-button-primary" @click="showAddPositionSearchMember">
        <i class="el-icon-circle-plus-outline"></i>
        <span style="margin-left:5px">添加新项目{{ permissionSelectedRole }}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionSetting.configDialog.visible = false" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!--  权限管理模块添加负责人或者成员  -->
    <el-dialog :title="permissionSetting.addDialog.title" width="500px"
               :visible.sync="permissionSetting.addDialog.visible"
               element-loading-background="#FFFFFF">
      <el-row :gutter="10">
        <el-col :span="18">
          <el-input @keyup.enter.native="addPositionSearchMember"
                    v-model="permissionSetting.addDialog.inputValue"
                    placeholder="请输入用户名，按回车确认"
                    :disabled="permissionSetting.addDialog.loading"
                    suffix-icon="el-icon-search"
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-button style="width: 100%" plain type="primary" icon="el-icon-search"
                     @click="addPositionSearchMember"
                     :disabled="permissionSetting.addDialog.loading"
          >搜 索</el-button>
        </el-col>
      </el-row>
      <el-table :data="permissionSetting.addDialog.users" v-loading="permissionSetting.addDialog.loading">
        <el-table-column prop="id" label="编号" width="50"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="module" label="所属模块" width="200"></el-table-column>
        <el-table-column prop="position" label="权限"></el-table-column>
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <i v-if="scope.row.canAdd" @click="addPosition(scope.$index)" class="el-icon-circle-plus-outline icon-button icon-button-primary"></i>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionSetting.addDialog.visible = false" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  loadPage,
  modUsername,
  modUserpwd,
  loadModuleLeaders,
  loadModuleMembers,
  searchMember,
  addUser,
  addModuleLeaders,
  addModuleMembers,
  delLeader,
  delMember,
  loadModuleLog,
} from "@/api/setting";
import config from "@/config";

export default {
  name: 'SystemSetting',
  data() {
    return {
      // 全局加载
      loading: false,
      // 当前用户角色，admin和root可以访问所有，normal只能访问用户名和密码
      permission: 'normal',
      // 菜单内容
      items: [
        {
          index: "identity",
          title: "用户名及密码",
          show: 'user',
        },
        {
          index: "permission",
          title: "项目权限管理",
          show: 'admin',
        },
        {
          index: "users",
          title: "用户管理",
          show: 'admin',
        },
        {
          index: "logs",
          title: "项目运行日志查看",
          show: 'admin',
        },
      ],
      // 当前选中
      activeIndex: 'identity',
      // 表格
      modules: [ 'GRAPES高分辨率确定性预报模式检验模块', 'GRAPES区域集合预报检验模块', '精细化小尺度大气扩散模式系统' ],
      identitySetting: {
        form: {
          updatingUsername: false,
          updatingPassword: false,
          oldUsername: '',//'张三',
          username: '',//'张三',
          oldPassword: '',//'123456',
          password: '',//'123456'
        }
      },
      permissionSetting: {
        selectedProject: 'GRAPES高分辨率确定性预报模式检验模块', //当前选中的项目
        selectedRole: 'leader',
        configDialog: {
          visible: false,
          loading: false,
          users: [
          ]
        },
        addDialog: {
          visible: false,
          loading: false,
          inputValue: '',
          title: '',
          users: [
            // {
            //   id: '013',
            //   name: '王二',
            //   module: 'GRAPES区域集合预报检验模块',
            //   position:'负责人',
            //   canAdd: true,
            // },
          ]
        }
      },
      userSetting: {
        searchForm: {
          value: ''
        },
        loading: false,
        list: [
          // {
          //   id: '013',
          //   name: '王二',
          //   module: 'GRAPES区域集合预报检验模块',
          // }
        ],
        dialog: {
          visible: false,
          loading: false,
          form: {
            username: '',
            password: '',
            password2: '',
            selectedProject: '',
            position: 'leader', //可选为‘leader’ 和 'memeber'
          }
        }
      },
      logSetting: {
        selectedProject: 'GRAPES高分辨率确定性预报模式检验模块', //当前选中的项目
        pageNum: 13, //日志总页数
        pageSize: 10, //一页日志总数
        currentPage: 1,
        loading: false,
        logs: [
          // {
          //   marker: 'info',
          //   info: 'load 2020EMSE data from ftp server',
          //   time: '2020-09-21  08:50:08'
          // },
        ]
      }
    };
  },
  methods: {
    changeLogPageSize(val) {
      this.logSetting.currentPage = 1;
      this.logSetting.pageSize = val;
      this.loadLog();
    },
    changeLogPage(val) {
      this.logSetting.currentPage = val;
      this.loadLog();
    },
    loadLog() {
      this.logSetting.loading = true;
      const {currentPage: page, pageSize, selectedProject: module} = this.logSetting;
      const reqData = {module, page, pageSize};
      loadModuleLog(reqData).then(({data}) => {
        this.logSetting.logs = data.logs;
        this.logSetting.pageNum = data.pageNum;
      }).finally(() => this.logSetting.loading = false);
    },
    permissionConfigureUser(role) {
      this.permissionSetting.configDialog.users = [];
      this.permissionSetting.selectedRole = role;
      this.permissionSetting.configDialog.visible = true;
      this.permissionSetting.configDialog.loading = true;

      const reqData = {
        module: this.permissionSetting.selectedProject,
      }
      let req = null;
      if (role === 'leader') {
        req = loadModuleLeaders(reqData);
      } else {
        req = loadModuleMembers(reqData);
      }
      req.then(({data}) => this.permissionSetting.configDialog.users = data)
        .finally(() => this.permissionSetting.configDialog.loading = false);
    },
    // 点击修改用户名时，先记录旧的用户名
    editUsername() {
      this.identitySetting.form.oldUsername = this.identitySetting.form.username;
      this.identitySetting.form.updatingUsername = true
    },
    // 点击修改用户名时，先记录旧的密码
    editPassword() {
      this.identitySetting.form.oldPassword = this.identitySetting.form.password;
      this.identitySetting.form.updatingPassword = true
    },
    updateUsername() {
      // 修改用户名
      const name = this.identitySetting.form.oldUsername;
      const new_name = this.identitySetting.form.username;
      modUsername({name, new_name}).then(res => {
        if (res.data.status === config.STATUS_SUCCESS) {
          this.$message({
            type: 'success',
            message: '修改用户名成功'
          });
        } else {
          this.identitySetting.form.username = this.identitySetting.form.oldUsername;
          this.$message({
            type: 'error',
            message: '修改用户名失败'
          });
        }
      })
      this.identitySetting.form.updatingUsername = false;
    },
    updatePassword() {
      // 修改密码
      const name = this.identitySetting.form.username;
      const new_pwd = this.identitySetting.form.password;
      modUserpwd({name, new_pwd}).then(res => {
        if (res.data.status === config.STATUS_SUCCESS) {
          this.$message({
            type: 'success',
            message: '修改密码成功'
          });
        } else {
          this.identitySetting.form.password = this.identitySetting.form.oldPassword;
          this.$message({
            type: 'error',
            message: '修改密码失败'
          });
        }
      });
      this.identitySetting.form.updatingPassword = false;
    },
    loadPage() {
      this.loading = true;
      loadPage().then(({data}) => {
        this.identitySetting.form.username = data.name;
        this.identitySetting.form.password = data.pwd;
        this.modules = data.modules;
        const { chooseModule } = data;
        this.userSetting.dialog.form.selectedProject = chooseModule;
        this.logSetting.selectedProject = chooseModule;
        this.permissionSetting.selectedProject = chooseModule;
        this.logSetting.logs = data.logs;
        this.logSetting.pageNum = data.pageNum;
        this.userSetting.list = data.userSamples;
        this.permission = data.permission;
      }).finally(() => this.loading = false);
    },
    // 用户管理搜索用户
    searchMember() {
      const name = this.userSetting.searchForm.value;
      this.userSetting.list = [];
      this.userSetting.loading = true;
      searchMember({name}).then(({data}) => {
        data.forEach(u => u.position = u.position === 'leader' ? '负责人' : '成员');
        this.userSetting.list = data;
        if(!data || !data.length) {
          this.$message.warning('查无此人')
        }
      }).finally(() => this.userSetting.loading = false);
    },
    showAddUser() {
      this.clearAddUser();
      this.userSetting.dialog.loading = false;
      this.userSetting.dialog.visible = true;
    },
    clearAddUser() {
      this.userSetting.dialog.form.username = '';
      this.userSetting.dialog.form.password = '';
      this.userSetting.dialog.form.password2 = '';
    },
    addUser() {
      this.userSetting.dialog.loading = true;
      const {username, password, password2, selectedProject, position} = this.userSetting.dialog.form;
      if (password === null || password === '') {
        this.$message({
          type: 'error',
          message: '请输入密码',
        });
        this.userSetting.dialog.loading = false;
        return;
      }
      if (password !== password2 ) {
        this.$message({
          type: 'error',
          message: '两次输入密码不一致，请重新输入',
        });
        this.userSetting.dialog.loading = false;
        return;
      }
      if (selectedProject === null || selectedProject === '') {
        this.$message({
          type: 'error',
          message: '请选择项目模块',
        });
        this.userSetting.dialog.loading = false;
        return;
      }
      const reqData = {
        name: username,
        pwd: password,
        module: selectedProject,
        position: position,
      };
      addUser(reqData).then(({data}) => {
        if (data.status === this.$config.STATUS_SUCCESS) {
          this.$message({
            type: 'success',
            message: '新增用户成功',
          });
        } else {
          this.$message({
            type: 'error',
            message: '新增用户失败',
          });
        }
      }).finally(() => {
        this.userSetting.dialog.loading = false;
        this.userSetting.dialog.visible = false;
        this.clearAddUser();
      })
    },
    showAddPositionSearchMember() {
      const selectedPosition = this.permissionSetting.selectedRole === 'leader' ? '负责人' : '成员';
      const selectedModule = this.permissionSetting.selectedProject;

      this.permissionSetting.addDialog.visible = true;
      this.permissionSetting.addDialog.users = [];
      this.permissionSetting.addDialog.inputValue = '';
      this.permissionSetting.addDialog.title = `${selectedModule} \n添加${selectedPosition}`;
    },
    // 权限管理搜索用户
    addPositionSearchMember() {
      this.permissionSetting.addDialog.users = [];
      this.permissionSetting.addDialog.loading = true;
      const name = this.permissionSetting.addDialog.inputValue;
      const selectedPosition = this.permissionSetting.selectedRole;
      const selectedModule = this.permissionSetting.selectedProject;
      searchMember({name}).then(({data}) => {
        data.forEach(u => {
          u.canAdd = !(u.module === selectedModule && u.position === selectedPosition);
          u.position = u.position === 'leader' ? '负责人' : '成员'
        });
        if(!data || !data.length) {
          this.$message.warning('查无此人')
        }
        this.permissionSetting.addDialog.users = data;
      }).finally(() => this.permissionSetting.addDialog.loading = false)
    },
    addPosition(index) {
      this.permissionSetting.addDialog.loading = true;
      const user = this.permissionSetting.addDialog.users[index];
      const selectedPosition = this.permissionSetting.selectedRole;
      const selectedModule = this.permissionSetting.selectedProject;
      const reqData = {
        id: user.id,
        module: selectedModule,
      };
      let req = null;
      if (selectedPosition === 'leader') {
        req = addModuleLeaders(reqData);
      } else {
        req = addModuleMembers(reqData);
      }
      req.then(({data}) => {
        if (data.status === this.$config.STATUS_SUCCESS) {
          this.$message({
            type: 'success',
            message: '新增成功',
          });
          user.canAdd = false;
          this.permissionConfigureUser(selectedPosition);
        } else {
          this.$message({
            type: 'error',
            message: '新增失败',
          });
        }
      }).finally(() => this.permissionSetting.addDialog.loading = false);
    },
    deletePosition(index) {
      this.permissionSetting.configDialog.loading = true;
      const user = this.permissionSetting.configDialog.users[index];
      const selectedPosition = this.permissionSetting.selectedRole;
      const selectedModule = this.permissionSetting.selectedProject;
      const reqData = {
        id: user.id,
        module: selectedModule,
      };
      let req = null;
      if (selectedPosition === 'leader') {
        req = delLeader(reqData);
      } else {
        req = delMember(reqData);
      }
      req.then(({data}) => {
        if (data.status === this.$config.STATUS_SUCCESS) {
          this.$message({
            type: 'success',
            message: '删除成功',
          });
          this.permissionSetting.configDialog.users.splice(index, 1);
        } else {
          this.$message({
            type: 'error',
            message: '删除失败',
          });
        }
      }).finally(() => this.permissionSetting.configDialog.loading = false);
    },
  },
  created() {
    this.loadPage();
  },
  computed: {
    permissionSelectedRole() {
      return this.permissionSetting.selectedRole === 'leader' ? '负责人' : '成员';
    },
    permissionDialogTitle() {
      const role = this.permissionSelectedRole;
      const selectedProject = this.permissionSetting.selectedProject;
      return this.modules.find(e => e === selectedProject) + `\n项目${role}配置`;
    },
    isAdmin() {
      return this.permission === 'admin' || this.permission === 'root';
    },
    isUser() {
      return ['admin', 'root', 'normal'].includes(this.permission);
    },
  }
}
</script>

<style lang="scss" scoped>
.icon-container {
  height: 32px;
  line-height: 32px;
  margin-right: 50px;
  .el-icon-edit {
    color: #666666;
    cursor: pointer;
  }
}
.dashboard {
  .icon-button {
    font-size: 1.2em;
    cursor: pointer;
  }
  .icon-button-danger {
    &:hover {
      color: #FD5A5A;
    }
  }
  .icon-button-primary {
    &:hover {
      color: #409EFF;
    }
  }
  .custom-button {
    font-size: 1.1em;
    cursor: pointer;
    margin: 10px 0;

  }
}
.warn {
  color: orange;
}
.error {
  color: red;
}
.info {
  color: #4EAC5B;
}

</style>